import type { ChildProcess } from 'child_process'
import treeKill from 'tree-kill'

/**
 * 杀死进程
 */
export function kill(child: ChildProcess) {
  return new Promise<void>((resolve, reject) => {
    if (child.pid) {
      treeKill(child.pid, (err) => {
        if (err) {
          reject(err)
        } else {
          resolve()
        }
      })
    } else {
      try {
        if (child.kill('SIGKILL')) {
          resolve()
        } else {
          reject(new Error('kill failed'))
        }
      } catch (e) {
        reject(e)
      }
    }
  })
}
